/** 认证相关的工具 */
import {session_duration_sec} from '../assets/settings.json'


/**
 * Description: 凭证.
 * @author <a href="mailto:scorpio.caplike@gmail.com">LiKe</a> @ 2025-03-08 23:51:49
 */
type Principal = {
    id: string,
    name: string,
    nickname: string,
    token?: string,
    since: number
}

const PRINCIPAL_KEY = 'principal'

export function setPrincipal(principal: Principal) {
    localStorage.setItem(PRINCIPAL_KEY, JSON.stringify(principal));
}

export function delPrincipal() {
    localStorage.removeItem(PRINCIPAL_KEY);
}

export function getCertainPrincipal(): Principal {
    return JSON.parse(localStorage.getItem(PRINCIPAL_KEY) as string);
}

export function getPrincipal(): Promise<Principal> {
    return new Promise((resolve, reject) => {
        const value = localStorage.getItem(PRINCIPAL_KEY)

        if (!value) {
            reject("凭证不存在")
            return
        }

        const principal: Principal = JSON.parse(value)
        if (Date.now() - principal.since > session_duration_sec * 1000) {
            reject("凭证已过期")
            return
        }

        resolve(principal)
    })
}

/**
 * Description: 如果存在, 刷新凭证.
 *
 * @author <a href="mailto:scorpio.caplike@gmail.com">LiKe</a> @ 2025-03-09 11:10:46
 */
export function renewPrincipalIfExists(): Promise<Principal> {
    return new Promise((resolve, reject) => {
        getPrincipal().then((principal: Principal) => {
            principal.since = Date.now()
            setPrincipal(principal)
            resolve(principal)
        }).catch((err) => {
            reject(err)
        })
    })
}

export function isAdmin(): boolean {
    const principal = getCertainPrincipal();
    return principal.name === 'admin'
}
